package top.zhaoyuliu.logbook.client.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hutool.core.util.StrUtil;

public final class IPUtils {

	private static Logger log = LoggerFactory.getLogger(IPUtils.class.getName());

	private static String locaIp = "";

	private IPUtils() {
	}

	/**
	 * 获取本机IP
	 * 
	 * @return
	 */
	public static String getIP() {
		try {
			return getIpAdd();
		} catch (SocketException e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * 根据网卡获得IP地址
	 * 
	 * @return
	 * @throws SocketException
	 */
	public static String getIpAdd() throws SocketException {
		if (StrUtil.isNotBlank(locaIp)) {
			return locaIp;
		}
		String ip = "";
		long minIp = Long.MAX_VALUE;
		for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
			NetworkInterface networkInterface = en.nextElement();
			String name = networkInterface.getName();
			if (!name.contains("docker") && !name.contains("lo") && !name.contains("br") && !name.contains("vet")) {
				for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr
						.hasMoreElements();) {
					// 获得IP
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						String ipAddress = inetAddress.getHostAddress();
						if (StrUtil.isBlank(ipAddress)) {
							continue;
						}
						if (!ipAddress.contains(":") && !ipAddress.contains("0:0:") && !ipAddress.contains("fe80")) {
							long intIP = Long.parseLong(ipAddress.replaceAll("\\.", ""));
							// 多个IP取最小的
							if (!"127.0.0.1".equals(ip) && minIp > intIP) {
								ip = ipAddress;
								minIp = intIP;
							}
						}
					}
				}
			}
		}
		locaIp = ip;
		return ip;
	}

	public static void main(String[] args) {
		try {
			System.out.println(getIpAdd());
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
